<template>
  <div class="table-container">
    <table>
      <thead>
        <tr>
          <th v-for="item in gridColumns" :key="item" @click="handleSortKey(item)" :class="{active: sortKey === item}">
            {{item}}
            <i class="el-icon-caret-top" v-show="sortKey === item && sortBy === 'asc'"></i>
            <i class="el-icon-caret-bottom" v-show="sortKey === item && sortBy === 'desc'"></i>
          </th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(item, index) in filterData" :key="index">
          <td v-for="(val, key, j) in item" :key="j">{{val}}</td>
        </tr>
      </tbody>
    </table>
  </div>
</template>
<script>
export default {
  name: 'GridData',
  props: {
    gridColumns: {
      type: Array,
      default: [],
    },
    gridData: {
      type: Array,
      default: [],
    },
    searchKey: {
      type: String,
      default: '',
    },
  },
	data(){
	  return {
	    // 默认name倒序排列
	    sortKey: '',
	    sortBy: '',
	  }
	},
  computed: {
    filterData(){
      if(!this.searchKey){
        // 没有关键字过滤时只考虑排序
        console.log(this.sortBy, this.sortKey)
        if(this.sortBy && this.sortKey){
          return this.sortData([...this.gridData])
        }else{
          return [...this.gridData]
        }
      }else{
        // 过滤list中含有关键字的item并排序
        let list = []
        list = this.gridData.filter(row => {
          return Object.keys(row).some(key => row[key].toString().toLowerCase().indexOf(this.searchKey) > -1)
        })
        return this.sortData([...list])
      }
    },
  },
  methods: {
    handleSortKey(key){
      this.sortKey = key
      this.sortBy = this.sortBy === 'desc' ? 'asc' : 'desc'
    },
    sortData(gridData){
      let list = []
      let result = []
      gridData.forEach(item => {
        list.push(item[this.sortKey])
      })
      if(this.sortBy === 'asc'){
        list.sort()
      }else{
        list.sort().reverse()
      }
      list.forEach(s => {
        gridData.forEach(item => {
          if(s === item[this.sortKey]){
            result.push(item)
          }
        })
      })
      return result
    }
  }
}
</script>
<style scoped>
  .active {
    color: red;
  }
	.table-container{
		text-align: center;
	}
	table{
		display: inline-block;
		width: 300px;
	}
</style>